package com.chenzp.rocketmq.contoller.listener;

import ch.qos.logback.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.StringMessageConverter;

/**
 * @Classname MyTransactionListener
 * @Description
 * @Version 1.0.0
 * @Date 2025-06-17 14:29
 * @Created by ncs
 */
@RocketMQTransactionListener
@Slf4j
public class MyTransactionListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.info("第一阶段确认事务消息{}", msg);
        org.apache.rocketmq.common.message.Message message = RocketMQUtil.convertToRocketMessage(new StringMessageConverter(), "utf-8", (String) arg, msg);
        String tags = message.getTags();
        if(StringUtil.isNullOrEmpty(tags)){
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        if(tags.contains("tagA")){
            return RocketMQLocalTransactionState.COMMIT;
        }else if(tags.contains("tagB")){
            return RocketMQLocalTransactionState.ROLLBACK;
        }else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        log.info("第二阶段确认事务消息{}", msg);
        return  RocketMQLocalTransactionState.ROLLBACK;
    }
}
